<template>
  <div class="app-container">
    <el-button-group style="margin-bottom: 16px;">
      <el-button @click="goTo('/content/help')">帮助中心</el-button>
      <el-button @click="goTo('/content/carousel')">轮播图</el-button>
      <el-button @click="goTo('/permission/role')">角色管理</el-button>
      <el-button @click="goTo('/system/basic')">系统配置</el-button>
    </el-button-group>
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="公告标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select
        v-model="listQuery.status"
        placeholder="公告状态"
        clearable
        style="width: 130px"
        class="filter-item"
      >
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="Plus"
        @click="handleCreate"
      >
        新增公告
      </el-button>
    </div>

    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" align="center" width="80">
        <template #default="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="公告标题" min-width="150px">
        <template #default="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="发布时间" width="180px" align="center">
        <template #default="scope">
          <span>{{ formatDate(scope.row.publishTime) }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="发布人" width="120px" align="center">
        <template #default="scope">
          <span>{{ scope.row.publisher }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="状态" width="120px" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button 
            v-if="scope.row.status === 0" 
            size="small" 
            type="success" 
            @click="handleModifyStatus(scope.row, 1)"
          >
            发布
          </el-button>
          <el-button 
            v-else 
            size="small" 
            type="info" 
            @click="handleModifyStatus(scope.row, 0)"
          >
            撤回
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="listQuery.page"
        v-model:page-size="listQuery.limit"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, post } from '@/utils/request'
import axios from 'axios'

const router = useRouter()
const goTo = (path: string) => router.push(path)

// 列表数据
const list = ref<Array<{ id: number; title: string; publishTime: string; publisher: string; status: number }>>([])
const total = ref(0)
const listLoading = ref(true)
const statusOptions = [
  { label: '草稿', value: 0 },
  { label: '已发布', value: 1 }
]

// 查询参数
const listQuery = reactive({
  page: 1,
  limit: 10,
  title: '',
  status: undefined
})

// 获取公告列表
const getList = async () => {
  listLoading.value = true
  try {
    // mock 数据
    const data = {
      code: 0,
      total: 2,
      items: [
        { id: 1, title: '系统维护公告', publishTime: '2024-05-01 10:00', publisher: '管理员', status: 1 },
        { id: 2, title: '新功能上线', publishTime: '2024-05-02 09:00', publisher: '超级管理员', status: 0 }
      ]
    }
    total.value = data.total
    list.value = data.items
  } finally {
    listLoading.value = false
  }
}

// 格式化日期
const formatDate = (date: string | number | Date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 搜索
const handleFilter = () => {
  listQuery.page = 1
  getList()
}

// 改变每页数量
const handleSizeChange = (val: number) => {
  listQuery.limit = val
  getList()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  listQuery.page = val
  getList()
}

// 新增公告
const handleCreate = () => {
  router.push('/content/announcement/add')
}

// 编辑公告
const handleUpdate = (row: any) => {
  router.push(`/content/announcement/edit/${row.id}`)
}

// 删除公告
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该公告吗？', '提示', { type: 'warning' })
    await axios.delete(`/api/announcement/${row.id}`)
    ElMessage.success('删除成功')
    getList()
  } catch {}
}

// 修改公告状态
const handleModifyStatus = async (row: any, status: number) => {
  try {
    await post(`/announcements/status`, { id: row.id, status })
    ElMessage.success('状态更新成功')
    getList()
  } catch {}
}

// 组件挂载时获取列表数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .filter-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.link-type {
  color: var(--primary-100);
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}
</style> 